﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Spreadsheets;
using System.IO;
using System.Threading;

namespace News_Roster
{
    public partial class Form1 : Form
    {
        SpreadsheetsService myService;
        ListFeed listFeed;
        TimeSpan interval = TimeSpan.FromSeconds(1000000);
        MethodDelegate dlgt;
        DataTable table;

        public Form1()
        {
            InitializeComponent();
            
            dlgt = new MethodDelegate(this.Refresh);
           
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            if (btnGo.Text == "Login")
                Login();
            btnAdd.Enabled = false;
            btnGo.Text = "Login";
            LoadList();
            btnAdd.Enabled = true;
            btnGo.Text = "Refresh";
            dataGridView1.DataSource = table;
            IAsyncResult ar = dlgt.BeginInvoke(new AsyncCallback(callback), "Call Executed");
            //dlgt();
            
            
        }

        static void callback(IAsyncResult ar)
        {
            
        }

        delegate void MethodDelegate();

        public void Refresh()
        {
            DateTime lastUpdate = DateTime.Now;
            while (true)
            {
                if (DateTime.Now.Add(-interval) > lastUpdate)
                {
                    lastUpdate = DateTime.Now;
                    LoadList();
                    MethodInvoker action = delegate { dataGridView1.DataSource = table; };
                    dataGridView1.Invoke(action);
                }
                
                Thread.Sleep(TimeSpan.FromSeconds(5));
            }
            
        }

        

        private void Login()
        {
            Log("Setting up login information");
            myService = new SpreadsheetsService("OMG!Droid News Roster July 2012");
            myService.setUserCredentials(txtUser.Text, txtPass.Text);
        }

        private void LoadList()
        {
            try
            {
                table = new DataTable();
                
                table.Columns.Add("Title");
                table.Columns.Add("Source");
                table.Columns.Add("Found By");
                table.Columns.Add("Posted By");
                table.Columns.Add("Post Type");
                table.Columns.Add("Date Found");
                table.Columns.Add("Date Published");
                Log("Connecting to server");
                SpreadsheetQuery query = new SpreadsheetQuery();
                SpreadsheetFeed feed = myService.Query(query);

                Log("Your spreadsheets:");
                SpreadsheetEntry roster = null;
                int i = 0;
                int index = 0;
                foreach (SpreadsheetEntry entry in feed.Entries)
                {
                    Log(entry.Title.Text);
                    if (entry.Title.Text == "OMG!Droid News Roster July 2012")
                    {
                        index = i;
                        roster = entry;
                    }
                    i++;
                }
                if (roster == null)
                {
                    Log("Roster not found.  Please check your login.");
                    MessageBox.Show("Roster not found.  Please check your login.");
                    return;
                }

                WorksheetFeed wsFeed = roster.Worksheets;
                WorksheetEntry worksheetEntry = (WorksheetEntry)wsFeed.Entries[0];
                Log("Worksheet loaded");
                AtomLink cellFeedLink = worksheetEntry.Links.FindService(GDataSpreadsheetsNameTable.CellRel, null);
                AtomLink listFeedLink = worksheetEntry.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null);

                ListQuery listQuery = new ListQuery(listFeedLink.HRef.ToString());
                listFeed = myService.Query(listQuery);
                Log("Reading Cells");
                CellQuery cquery = new CellQuery(cellFeedLink.HRef.ToString());
                CellFeed cfeed = worksheetEntry.QueryCellFeed(ReturnEmptyCells.yes);

                
                
                DataRow row = null;
                foreach (CellEntry curCell in cfeed.Entries)
                {
                    if (curCell.Row == 1)
                    {

                    }
                    else
                    {
                        if (curCell.Cell.Column == 1)
                        {
                            try
                            {
                                table.Rows.Add(row);
                            }
                            catch { }
                            row = table.NewRow();
                        }
                        row[Int32.Parse(curCell.Cell.Column.ToString()) - 1] = curCell.Cell.Value;
                        //richTextBox1.Text += "Row " + curCell.Row.ToString() + ", column " + curCell.Cell.Column.ToString() + ": " + curCell.Cell.Value;
                    }
                }
                table.Rows.Add(row);
                Log("Finished reading, displaying table");
                

                
                
                //AddRow();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                Log(e.Message);
            }

        }

        private void Log(string note)
        {
            using (StreamWriter sw = new StreamWriter("log.txt",true))
            {
                sw.WriteLine(DateTime.Now.ToString() + ": " + note);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            Log("New row being added");
            frmNew newRow = new frmNew();
            if (newRow.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ListEntry row = new ListEntry();
                
                row.Elements.Add(new ListEntry.Custom() { LocalName = "title", Value = newRow.Title });
                row.Elements.Add(new ListEntry.Custom() { LocalName = "source", Value = newRow.Source });
                row.Elements.Add(new ListEntry.Custom() { LocalName = "foundby", Value = newRow.FoundBy });
                row.Elements.Add(new ListEntry.Custom() { LocalName = "postedby", Value = newRow.PostedBy });
                row.Elements.Add(new ListEntry.Custom() { LocalName = "posttype", Value = newRow.PostType });
                row.Elements.Add(new ListEntry.Custom() { LocalName = "datefound", Value = newRow.DateFound });
                row.Elements.Add(new ListEntry.Custom() { LocalName = "datepublished", Value = newRow.DatePublished });
                try
                {
                    //myService.Insert(listFeed, row);
                    listFeed.Insert(row);
                    Log("Inserting new row");
                    //MessageBox.Show("Success!");
                }
                catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        Log(ex.Message);
                    }
            }
        }

        private void AddRow()
        {
            ListEntry row = new ListEntry();

            row.Elements.Add(new ListEntry.Custom() { LocalName = "title", Value = "test" });
            row.Elements.Add(new ListEntry.Custom() { LocalName = "source", Value = "test" });
            row.Elements.Add(new ListEntry.Custom() { LocalName = "foundby", Value = "test" });
            row.Elements.Add(new ListEntry.Custom() { LocalName = "postedby", Value = "test" });
            row.Elements.Add(new ListEntry.Custom() { LocalName = "posttype", Value = "test" });
            row.Elements.Add(new ListEntry.Custom() { LocalName = "datefound", Value = "7/18/2012" });
            row.Elements.Add(new ListEntry.Custom() { LocalName = "datepublished", Value = "7/18/2012" });
            
            try
            {
                myService.Insert(listFeed, row);
                listFeed.Insert(row);
                MessageBox.Show("Success!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            int column = e.ColumnIndex;
            int row = e.RowIndex;
            try
            {
                Log("Setting Value " + dataGridView1.Rows[row].Cells[column].Value.ToString() + " to " + column.ToString() + "," + row.ToString());
                ListEntry lRow = (ListEntry)listFeed.Entries[row];
                lRow.Elements[column].Value = dataGridView1.Rows[row].Cells[column].Value.ToString();
                lRow.Update();
                Log("Set");
                refreshListFeed();
            }
            catch (ArgumentOutOfRangeException)
            {
                MessageBox.Show("For a new row, please use the new row button at the top");
            }

        }

        private void refreshListFeed()
        {
            Log("Connecting to server for refresh");
            SpreadsheetQuery query = new SpreadsheetQuery();
            SpreadsheetFeed feed = myService.Query(query);
            SpreadsheetEntry roster = null;
            
            foreach (SpreadsheetEntry entry in feed.Entries)
            {
                if (entry.Title.Text == "OMG!Droid News Roster July 2012")
                {
                    roster = entry;
                    break;
                }
            }
            if (roster == null)
            {
                MessageBox.Show("Roster not found.  Please check your login.");
                return;
            }

            WorksheetFeed wsFeed = roster.Worksheets;
            WorksheetEntry worksheetEntry = (WorksheetEntry)wsFeed.Entries[0];
            AtomLink listFeedLink = worksheetEntry.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null);
            ListQuery listQuery = new ListQuery(listFeedLink.HRef.ToString());
            listFeed = myService.Query(listQuery);
            Log("Completed");
        }

        private void txtUser_Leave(object sender, EventArgs e)
        {
            if (!txtUser.Text.Contains("@gmail.com"))
                txtUser.Text += "@gmail.com";
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int seconds = 0;
            switch (comboBox1.SelectedItem.ToString())
            {
                case "Manual":
                    seconds = int.MaxValue;
                    break;
                case "10 Seconds":
                    seconds = 10;
                    break;
                case "30 Seconds":
                    seconds = 30;
                    break;
                case "1 Minute":
                    seconds = 60;
                    break;
                case "2 Minutes":
                    seconds = 120;
                    break;
                case "5 Minutes":
                    seconds = 300;
                    break;
            }

            interval = TimeSpan.FromSeconds(seconds);
        }   
    }
}
